package com.sunday.pinxinghui.widgets;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;


import com.aigestudio.wheelpicker.WheelPicker;
import com.sunday.common.base.BaseActivity;
import com.sunday.common.model.ResultDO;
import com.sunday.common.utils.DeviceUtils;
import com.sunday.pinxinghui.R;
import com.sunday.pinxinghui.entity.Product;
import com.sunday.pinxinghui.entity.Province;
import com.sunday.pinxinghui.network.ApiClient;


import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * Created by 刘涛 on 2016/11/2.
 */

public class SelectCityWindow extends PopupWindow implements View.OnClickListener {

    private Context mContext;

    boolean isCanReturn = false;
    int LoadLevel = 1;//加载数据等级  1是省 2是市 3是区

    //省市区ID
    int provinceId;
    int cityId;
    int areaId;
    Province province;
    Province city;
    Province area;
    List<Province> provinList = new ArrayList<>();
    List<Province> cityList = new ArrayList<>();
    List<Province> areaList = new ArrayList<>();
    List<String> provinceNames=new ArrayList<String>();
    List<String> cityNames=new ArrayList<String>();
    List<String> areaNames=new ArrayList<String>();
    int fatherId = 0;//父类ID

    private View windowView;
    WheelPicker wheelProvince;
    WheelPicker wheelCity;
    WheelPicker wheelArea;
    LinearLayout llSelete;
    TextView btnConfirm;
    TextView btnCancel;

    private int appWith, appHeight;


    public SelectCityWindow(Context context) {
        this.mContext = context;
        appWith = DeviceUtils.getDisplay(mContext).widthPixels;
        appHeight = DeviceUtils.getDisplay(mContext).heightPixels;
        windowView = LayoutInflater.from(mContext).inflate(R.layout.select_city, null);
        this.setContentView(windowView);
        this.setOutsideTouchable(true);
        this.setFocusable(true);
        this.setWidth(appWith);
        this.setHeight(appHeight / 3);
        this.setOnDismissListener(new PoponDismissListener());
        this.setBackgroundDrawable(new BitmapDrawable());
        this.setOutsideTouchable(true);
        this.setAnimationStyle(R.style.popuwindow);
        wheelProvince = (WheelPicker) windowView.findViewById(R.id.wheel_province);
        wheelCity = (WheelPicker) windowView.findViewById(R.id.wheel_city);
        wheelArea = (WheelPicker) windowView.findViewById(R.id.wheel_area);
        llSelete = (LinearLayout) windowView.findViewById(R.id.ll_selete);
        btnConfirm = (TextView) windowView.findViewById(R.id.btn_confirm);
        btnCancel = (TextView) windowView.findViewById(R.id.btn_cancel);
        initView();
        loadData();
        btnConfirm.setOnClickListener(this);
        btnCancel.setOnClickListener(this);
    }

    private void initView() {
        wheelProvince.setVisibility(View.INVISIBLE);
        wheelCity.setVisibility(View.INVISIBLE);
        wheelArea.setVisibility(View.INVISIBLE);
        //省
        wheelProvince.setSelectedItemPosition(0);
        wheelProvince.setOnWheelChangeListener(new WheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolled(int i) {

            }

            @Override
            public void onWheelSelected(int i) {
//滚动结束后事件
                if (provinList.size() <= i) {
                    return;
                }
                fatherId = provinList.get(i).getId();
                provinceId = provinList.get(i).getId();
                province = provinList.get(i);
                LoadLevel = 2;
                loadData();
                ((BaseActivity) mContext).showLoadingDialog(0);
                isCanReturn = true;
            }

            @Override
            public void onWheelScrollStateChanged(int i) {

            }
        });

        //市
        wheelCity.setSelectedItemPosition(0);
        wheelCity.setOnWheelChangeListener(new WheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolled(int i) {

            }

            @Override
            public void onWheelSelected(int i) {
               //滚动结束后
                if (cityList.size() <= i) {
                    return;
                }
                fatherId = cityList.get(i).getId();
                cityId = cityList.get(i).getId();
                city = cityList.get(i);
                LoadLevel = 3;
                loadData();
                ((BaseActivity) mContext).showLoadingDialog(0);
                isCanReturn = true;
            }

            @Override
            public void onWheelScrollStateChanged(int i) {

            }
        });


        //区
        wheelArea.setSelectedItemPosition(0);
        wheelArea.setOnWheelChangeListener(new WheelPicker.OnWheelChangeListener() {
            @Override
            public void onWheelScrolled(int i) {

            }

            @Override
            public void onWheelSelected(int i) {
                //滚动结束后选中的值
                if (areaList.size() <= i) {
                    return;
                }
                areaId = areaList.get(i).getId();
                area = areaList.get(i);
                isCanReturn = true;
            }

            @Override
            public void onWheelScrollStateChanged(int i) {

            }
        });
    }

    private void loadData() {
        switch (LoadLevel) {
            case 1://省
                Call<ResultDO<List<Province>>> call = ApiClient.getApiAdapter().getProvince();
                call.enqueue(new Callback<ResultDO<List<Province>>>() {
                    @Override
                    public void onResponse(Call<ResultDO<List<Province>>> call, Response<ResultDO<List<Province>>> response) {
                        ((BaseActivity) mContext).dissMissDialog();
                        if (response.body() == null) {
                            return;
                        }
                        if (response.body().getCode() == 0) {
                            provinList.clear();
                            provinList.addAll(response.body().getResult());
                            if (provinList == null || provinList.size() == 0) {
                                return;
                            }
                     provinceNames.clear();
                            for (Province province:provinList){
                                provinceNames.add(province.getName());
                            }
                            fatherId = provinList.get(0).getId();
                            provinceId = provinList.get(0).getId();
                            province = provinList.get(0);
                            wheelProvince.setData(provinceNames);
                            wheelProvince.invalidate();
                            //加载市
                            LoadLevel = 2;
                            loadData();
                            wheelProvince.setVisibility(View.VISIBLE);
                        } else {
                            wheelProvince.setVisibility(View.INVISIBLE);
                            wheelCity.setVisibility(View.INVISIBLE);
                            wheelArea.setVisibility(View.INVISIBLE);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultDO<List<Province>>> call, Throwable t) {
                        ((BaseActivity) mContext).dissMissDialog();
                    }
                });
                break;
            case 2:
                Call<ResultDO<List<Province>>> call1 = ApiClient.getApiAdapter().getCity(fatherId);
                call1.enqueue(new Callback<ResultDO<List<Province>>>() {
                    @Override
                    public void onResponse(Call<ResultDO<List<Province>>> call, Response<ResultDO<List<Province>>> response) {
                        ((BaseActivity) mContext).dissMissDialog();
                        if (response.body() != null && response.body().getCode() == 0) {
                            cityList.clear();
                            cityList.addAll(response.body().getResult());
                            if (cityList == null || cityList.size() == 0) {
                                return;
                            }
                            fatherId = cityList.get(0).getId();
                            cityId = cityList.get(0).getId();
                            city = cityList.get(0);
                            cityNames.clear();
                            for (Province province:cityList){
                                cityNames.add(province.getName());
                            }
                            wheelCity.setData(cityNames);
                            wheelCity.invalidate();
                            //加载市
                            LoadLevel = 3;
                            loadData();
                            wheelCity.setVisibility(View.VISIBLE);
                        } else {
                            wheelCity.setVisibility(View.INVISIBLE);
                            wheelArea.setVisibility(View.INVISIBLE);
                        }
                    }

                    @Override
                    public void onFailure(Call<ResultDO<List<Province>>> call, Throwable t) {
                        ((BaseActivity) mContext).dissMissDialog();
                    }
                });
                break;
            case 3://区
                Call<ResultDO<List<Province>>> call2 = ApiClient.getApiAdapter().getDistrict(fatherId);
                call2.enqueue(new Callback<ResultDO<List<Province>>>() {
                    @Override
                    public void onResponse(Call<ResultDO<List<Province>>> call, Response<ResultDO<List<Province>>> response) {
                        ((BaseActivity) mContext).dissMissDialog();
                        if (response.body() != null && response.body().getCode() == 0) {
                            areaList.clear();
                            areaList.addAll(response.body().getResult());
                            if (areaList == null || areaList.size() == 0) {
                                return;
                            }
                            if (response.body().getResult() != null) {
                                areaList.addAll(response.body().getResult());
                            }
                            if (areaList.size() > 0) {
                                areaId = areaList.get(0).getId();
                                area = areaList.get(0);
                            } else {
                                area = null;
                                areaId = 0;
                            }
                            areaNames.clear();
                            for (Province province:areaList){
                                areaNames.add(province.getName());
                            }
                            wheelArea.setData(areaNames);
                            wheelArea.invalidate();
                            wheelArea.setVisibility(View.VISIBLE);
                            isCanReturn = true;
                        } else {
                            wheelArea.setVisibility(View.INVISIBLE);
                        }

                    }

                    @Override
                    public void onFailure(Call<ResultDO<List<Province>>> call, Throwable t) {
                        ((BaseActivity) mContext).dissMissDialog();
                    }
                });
                break;
        }

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_confirm:
                if (!isCanReturn) {
                    return;
                }
                if (isCanReturn && onSelectListener != null) {
                    onSelectListener.onSelect(province, city, area);
                    backgroundAlpha(1f);
                    dismiss();
                }
                break;
            case R.id.btn_cancel:
                dismiss();
                break;
        }
    }

    //显示
    public void showPopupWindow(View parent) {
        if (!this.isShowing()) {
            backgroundAlpha(0.5f);
            this.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        } else {
            this.dismiss();
        }
    }

    private OnCitySelectListener onSelectListener;

    public void setOnSelectListener(OnCitySelectListener onSelectListener) {
        this.onSelectListener = onSelectListener;
    }


    public interface OnCitySelectListener {
        void onSelect(Province province, Province city, Province district);
    }


    /**
     * 弹出的popWin关闭的事件，主要是为了将背景透明度改回来
     */
    class PoponDismissListener implements PopupWindow.OnDismissListener {

        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            //Log.v("List_noteTypeActivity:", "我是关闭事件");
            backgroundAlpha(1f);
//            dismiss();
        }
    }


    /**
     * 设置添加屏幕的背景透明度
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = ((Activity) mContext).getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        ((Activity) mContext).getWindow().setAttributes(lp);
    }
}
